package com.codejiwei.akka;

/**
 * @author jiwei
 * @description
 * @date 2023/12/29 17:34
 */
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

// Sender Actor
class SenderActor extends AbstractActor {
    private final ActorRef receiverActor;

    public SenderActor(ActorRef receiverActor) {
        this.receiverActor = receiverActor;
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchAny(message -> {
                    receiverActor.tell(message, getSelf()); // 发送消息给 ReceiverActor
                })
                .build();
    }
}

// Receiver Actor
class ReceiverActor extends AbstractActor {
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchAny(message -> {
                    System.out.println("Received message: " + message);
                    getSender().tell("Message received", getSelf()); // 回复发送者
                })
                .build();
    }
}

public class AkkaMessagingExample {
    public static void main(String[] args) {
        // 创建 Actor 系统
        ActorSystem system = ActorSystem.create("akka-system");

        // 创建 ReceiverActor
        ActorRef receiverActor = system.actorOf(Props.create(ReceiverActor.class), "receiverActor");

        // 创建 SenderActor，并将 ReceiverActor 的引用传递给它
        ActorRef senderActor = system.actorOf(Props.create(SenderActor.class, receiverActor), "senderActor");

        // 发送消息给 ReceiverActor
        senderActor.tell("Hello ReceiverActor", ActorRef.noSender());

        // 关闭 Actor 系统
        system.terminate();
    }
}

